rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")


#4.1 用R的基础绘图系统作图
#4.1.1 函数plot
dose <- c(20, 30, 40, 45, 60)
drugA <- c(16, 20, 27, 40, 60)
drugB <- c(15, 18, 25, 31, 40)
#散点图
plot(dose, drugA)
#点线图
plot(dose, drugA, type = "b")
#用plot作图；用低水平作图函数优化
plot(dose, drugA, type = "b",
     xlab = "Dosage", ylab = "Response",
     lty = 1, pch = 15)#不同类型的线（lty）与点（pch）
lines(dose, drugB, type = "b", lty = 2, pch = 17)
#添加标签——图例中的点、线属性必须与前面一致
legend("topleft", title = "Drug Type",
       legend = c("A","B"),
       lty = c(1, 2),
       pch = c(15, 17))

rm(list = ls(all = TRUE))
#4.1.2 直方图和密度曲线图
data(anorexia, package = "MASS")
str(anorexia)
attach(anorexia)
hist(Prewt)
plot(density(Prewt))
hist(Prewt, freq = FALSE, col = "red",
     xlab = "体重（lbs）",
     main = "治疗前体重分布直方图",
     las = 1)#用las将纵轴的刻度标签横向显示
lines(density(Prewt), col = "blue", lwd = 2)#两倍于默认曲线宽度
#在横轴上添加轴须线没战士数据分布的密集程度
rug(Prewt)
detach(anorexia)
#4.1.3 条形图
#install.packages("vcd")
#install.packages("grid")
library(vcd)
data(Arthritis)
attach(Arthritis)
counts <- table(Improved)
counts
barplot(counts, xlab = "Improvement", ylab = "Frequency", las = 1)
#二维列联表
counts <- table(Improved, Treatment)
barplot(counts,
        col = c("red", "yellow","green"),
        xlab = "Improvement", ylab = "Frequency",
        beside = TRUE, las =1)
legend("top", legend = rownames(counts),
       fill = c("red","yellow","green"))
#简化步骤获取均值标准差条形图等
library(epiDisplay)
aggregate.plot(anorexia$Postwt, by = list(anorexia$Treat),
               error = "sd", legend = FALSE,
               #legend这里只能用逻辑词
               bar.col = c("red","yellow","green"),
               ylim = c(0,100), las = 1,
               main = "")

rm(list = ls())
#4.1.4 饼图
percent <- c(5.8, 27.0, 0.5, 20.8, 12.8, 33.1)
disease <- c("上感","中风","外伤","昏厥","食物中毒","其他")
lbs <- paste0(disease, percent, "%")
pie(percent, labels = lbs, col = rainbow(6))

#4.1.5 箱线图和小提琴图
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
boxplot(anorexia$wt.change, ylab = "Weight change (lbs)", las = 1)
#因变量~自变量
boxplot(wt.change ~ Treat, data = anorexia,
        ylab = "Weight change (lbs)", las = 1)
#install.packages("vioplot")
library(vioplot)
vioplot(wt.change ~ Treat, data = anorexia,
        ylab = "Weight change (lbs)",
        col = "gold", las = 1)

#4.1.6 克利夫兰点图
dotchart(VADeaths)
dotchart(VADeaths, pch = 19)

#4.1.7 导出图形
setwd("C:\\Users\\lenovo\\Desktop\\R")
pdf("mygraph.pdf")
boxplot(wt.change ~ Treat,
        data = anorexia,
        ylab = "Weight change (lbs)",
        las = 1)
boxplot(wt.change ~ Treat, data = anorexia, ylab = "Weight change(lbs)")
dev.off()
#tiff格式的图形文件可以支持多种色彩系统、独立于操作系统
tiff(filename = "mygraph.tiff",
     width = 15, height = 12, units = "cm", res = 300)
boxplot(wt.change ~ Treat, data = anorexia, 
        ylab = "Weight change (lbs)")
dev.off()

#4.2 用ggplot2包作图

#4.2.1 初识ggplot2包
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggplot2)
pdf("mygraph.pdf")
p <- ggplot(data = mtcars, mapping = aes(x = wt, y = mpg))
p + geom_point()
dev.off()

#不同转动方式（am）下，车重和耗油量的关系
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggplot2)
pdf("mygraph.pdf")
mtcars$am <- factor(mtcars$am)
ggplot(data = mtcars, aes(x = wt, y = mpg, color = am)) + geom_point()
ggplot(data = mtcars, aes(x = wt, y = mpg, shape = am)) + geom_point()
dev.off()

#对原始数据进行归纳后作图
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggplot2)
pdf("mygraph.pdf")
mtcars$am <- factor(mtcars$am)
#散点拟合曲线
ggplot(data = mtcars, aes(x = wt, y = mpg, color = am)) + geom_smooth()
#直线回归
ggplot(data = mtcars, aes(x = wt, y = mpg, color = am)) + 
        geom_smooth(method = "lm")
dev.off()

#有两条拟合线是因为将变量am映射为颜色属性；
#如果只想显示一条拟合线，需要在geom_point函数中单独设置颜色的映射
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggplot2)
pdf("mygraph.pdf")
mtcars$am <- factor(mtcars$am)
#只想显示一条平滑线
 ggplot(data = mtcars, aes(x = wt, y = mpg)) +
        geom_point(aes(color = am))+
        stat_smooth()

#用标度函数（scale）设定颜色
ggplot(data = mtcars, aes(x = wt, y = mpg))+
        geom_point(aes(color = am))+
        scale_color_manual(values = c("blue", "red"))+
        stat_smooth()

dev.off()

#实现lattice包中的分组绘图功能，即分面（facet）
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggplot2)
pdf("mygraph.pdf")
mtcars$am <- factor(mtcars$am)

ggplot(data = mtcars, aes(x = wt, y = mpg))+
        geom_point()+
        stat_smooth()+
        facet_grid(~am)

dev.off()

#使用theme函数定义绘图的风格
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggplot2)
pdf("mygraph.pdf")
mtcars$am <- factor(mtcars$am)

ggplot(data = mtcars, aes(x = wt, y = mpg))+
        geom_point(aes(color = am))+
        stat_smooth()+
        theme_bw()

dev.off()

#4.2.2 分布的特征
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
pdf("mygraph.pdf")
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
library(ggplot2)
ggplot(anorexia, aes(x = wt.change))+
        geom_histogram(binwidth = 2, fill = "skyblue", color = "black")+
        labs(x = "weight change (lbs)")+
        theme_bw()
dev.off()

#将直方图与密度曲线同时展示
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
pdf("mygraph.pdf")
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
library(ggplot2)
ggplot(anorexia, aes(x = wt.change, y = ..density..))+#设定y轴为频率密度
        geom_histogram(binwidth = 2, fill = "skyblue", color = "black")+
        stat_density(geom = "line", linetype = "dashed", size = 1)+#一种计算密度估计曲线的统计变换
        labs(x = "weight change (lbs)")+
        theme_bw()
dev.off()

#比较不同治疗方式下体重改变量的分布: 密度曲线图
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
pdf("mygraph.pdf")
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
library(ggplot2)
ggplot(anorexia, aes(x = wt.change, color = Treat, linetype = Treat))+
        stat_density(geom = "line", size = 1)+
        labs(x = "weight change (lbs)")+
        theme_bw()
dev.off()

#箱线图
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
pdf("mygraph.pdf")
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
library(ggplot2)
ggplot(anorexia, aes(x = Treat, y = wt.change, fill = Treat))+
       geom_boxplot()+
        theme_bw()
dev.off()

#在平行箱线图上添加组间比较的统计学差异
#install.packages("ggpubr")
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggpubr)
library(ggplot2)
my_comparisons <- list(c("CBT", "Cont"),c("CBT","FT"),c("Cont", "FT"))
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
pdf("mygraph.pdf")


ggplot(anorexia, aes(x = Treat, y = wt.change))+
        geom_boxplot()+
        stat_compare_means(comparisons = my_comparisons,
                           method = "t.test",
                           color = "blue")+
        theme_bw()

dev.off()

#用ggplot绘制小提琴图
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")
library(ggpubr)
library(ggplot2)
my_comparisons <- list(c("CBT", "Cont"),c("CBT","FT"),c("Cont", "FT"))
data(anorexia, package = "MASS")
anorexia$wt.change <- anorexia$Postwt - anorexia$Prewt
pdf("mygraph.pdf")


ggplot(anorexia, aes(x = Treat, y = wt.change, fill = Treat))+
        geom_violin()+
        geom_point(position = position_jitter(0.1),alpha = 0.5)+
        stat_compare_means(comparisons = my_comparisons,
                           method = "t.test",
                           color = "blue")+
        theme_bw()

dev.off()

#4.2.3 比例的构成
#条形图——纵坐标为计数的绝对大小
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")

library(ggplot2)

data(Arthritis, package = "vcd")

pdf("mygraph.pdf")

ggplot(Arthritis, aes(x = Treatment, fill = Improved))+
        #边框为黑色
        geom_bar(color = "black")+
        scale_fill_brewer()+
        theme_bw()

dev.off()

#条形图——纵坐标为计数的相对大小——参数position设为fill
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")

library(ggplot2)

data(Arthritis, package = "vcd")

pdf("mygraph.pdf")

ggplot(Arthritis, aes(x = Treatment, fill = Improved))+
        #边框为黑色
        geom_bar(color = "black", position = "fill")+
        scale_fill_brewer()+
        theme_bw()

dev.off()

#条形图——把条形图并排放置——参数position设为dodge
rm(list = ls())
setwd("C:\\Users\\lenovo\\Desktop\\R")

library(ggplot2)

data(Arthritis, package = "vcd")

pdf("mygraph.pdf")

ggplot(Arthritis, aes(x = Treatment, fill = Improved))+
        #边框为黑色
        geom_bar(color = "black", position = "dodge")+
        scale_fill_brewer()+
        theme_bw()

dev.off()

#4.2.4 用函数ggsave保存图形
#专门用于保存ggplot2包绘制的图形
p <- ggplot(mtcars, aes(wt, mpg))+geom_point()
ggsave("myplot.pdf",p)
ggsave("myplot.png",p)
ggsave("myplot.tiff",width = 15, height = 12, units = "cm", dpi = 500)


#4.3 其他图形
#4.3.1 金字塔图
library(epiDisplay)
pdf("mygraph.pdf")

data("Oswego")
pyramid(Oswego$age, Oswego$sex, col.gender = c(2,4), bar.label = TRUE)

dev.off()


#4.3.2 横向堆栈条形图
#install.packages("sjPlot")
#可视化流行病学、社会科学
library(sjPlot)
data(efc)
names(efc)
#查看数据集信息
view_df(efc)
#选取数据
qdata <- dplyr::select(efc, c82cop1:c90cop9)

pdf("mygraph.pdf")

plot_stackfrq(qdata)

dev.off()

#4.3.3 热图

data(mtcars)
dat <- scale(mtcars)
class(dat)

pdf("mygraph.pdf")

heatmap(dat)

dev.off()

#4.3.4 三维散点图
#install.packages("scatterplot3d")
library(scatterplot3d)
data(trees)

pdf("mygraph.pdf")
#type默认为p（点），设置为h（线）
#angle为x轴与y轴的角度
scatterplot3d(trees, type = "h", highlight.3d = T,
              angle = 55, pch = 16)

dev.off()

#交互式操作
#install.packages("rgl")
library(rgl)
plot3d(trees, type = "h")

#4.3.5 词云图
#install.packages("wordcloud2")
library(wordcloud2)
head(demoFreqC)
#不能制成pdf
wordcloud2(demoFreqC)
#文本挖掘：常用tm包，中文分词：Rwordseg包与jiebaR包
#install.packages("tm")
#install.packages("Rwordseg")
#install.packages("jiebaR")

#4.3.6 动态图形
#1 将一组png图片保存为.gif文件
#建立10幅png图形
for (i in 1:10) {
        png(file = paste0(i, ".png"))
        plot.new()
        text(0.5, 0.5, 11-i, cex = 6)
        dev.off()
}
#然后用在线工具或ImageMagick转换成.gif
#2 使用gganimate包生成.gif文件
#install.packages("gganimate")
library(ggplot2)
library(gganimate)
airquality$date <-
        as.Date(paste(1973, airquality$Month, airquality$Day, sep = "-"))
g <- ggplot(airquality, aes(date, Temp))+
        geom_line()+
#install.packages("transformr")
        transition_time(Month)+
#动画过渡的前半部分按照正弦函数的模式       
        ease_aes('sine-in-out')
anim_save(g, filename = "animation.gif")

#install.packages("anim.plots")
library(anim.plots)
anim.save(g, "animation.gif")





rm(list = ls(all = TRUE))
#习题

